import { _decorator, Animation, Button, Color, Component, director, find, Label, log, Node, Sprite, sys, tween, UITransform } from 'cc';
import { PipeLayer } from './PipeLayer';
import { Player } from './Player';
const { ccclass, property } = _decorator;

@ccclass('GameManager')
export class GameManager extends Component {
    // 开始按钮
    @property({ type: Button }) 
    startButton: Button;
    // 地面背景
    @property({ type: Node }) 
    groundBg: Node;
    // 小鸟飞行动画
    @property(Animation)
    birdAnim: Animation = null;
    // 过渡层
    @property(Sprite)
    maskLayer: Sprite = null;
    // 角色控制器
    @property({ type: Player }) 
    player: Player | null = null;
    // 管道控制器
    @property({ type: PipeLayer }) 
    pipeLayer: PipeLayer | null = null;
    // 当前得分与历史最佳
    @property(Label)
    currentScore: Label = null;
    @property(Label)
    bestScore: Label = null;
    // 背景滚动reset临界值
    _resetX: number = 0;
    // 返回按钮（重新开始游戏）
    @property({ type: Button }) 
    backButton: Button;
    /**
     * 初始化
     */
    start() {
        // 绑定自定义事件 GameEnd 监听结束
        this.player?.node.on('GameEnd', this.onGameEnd, this);
        // 开始菜单，小鸟自身动画
        if (this.birdAnim) {
            this.birdAnim.play('birdFlapping');
            this.birdAnim.play('birdWing');
        }
        // 绑定按钮点击事件
        this.startButton.node.on(Button.EventType.CLICK, this.pageToReady, this);
        this.backButton.node.on(Button.EventType.CLICK, this.reloadSence, this);
        // 设置背景滚动reset临界值
        this._resetX = -(find("Canvas").getComponent(UITransform).width);
        // 开始面板初始化
        find("Canvas/Main/Player").active = false;
        find("Canvas/Main/PipeLayer").active = false;
        find("Canvas/Main/Menu/Ready").active = false;
        find("Canvas/Main/Menu/End").active = false;
        this.blinkOnce();
        find("Canvas/Main/Menu/Home").active = true;
    }

    /**
     * 面板切换过渡：屏幕闪烁一下
     */
    blinkOnce() {
        this.maskLayer.color = Color.WHITE;
        tween(this.maskLayer).show().delay(0.1).hide().start();
    }

    /**
     * 点击按钮 打开 准备面板
     */
    pageToReady(){
        find("Canvas/Main/Menu/Home").active = false;
        this.blinkOnce();
        find("Canvas/Main/Menu/Ready").active = true;
        find("Canvas/Main/Menu/Ready").on(Node.EventType.TOUCH_START, this.onStartGame, this);
        find("Canvas/Main/Player").active = true;
        find("Canvas/Main/PipeLayer").active = true;
    }

    /**
     * 点击屏幕 开始游戏
     */
    onStartGame(){
        log("开始游戏")
        find("Canvas/Main/Menu/Ready").active = false;
        // 生成管道
        this.pipeLayer.startSpawn();
        this.blinkOnce();
        // 开始游戏
        this.player.startTheGame(this);
    }

    /**
     * 滚动地面
     */
    update(deltaTime: number) {
        // 滚动地面
        let posX = this.groundBg.getPosition().x -= 300 * deltaTime;
        let posY = this.groundBg.getPosition().y;
        this.groundBg.setPosition(posX, posY);
        if (posX <= this._resetX) {
            this.groundBg.setPosition(0, posY);
        }
    }

    /**
     * 绑定自定义事件 GameEnd 监听结束
     */
    private onGameEnd(score: number) {
        // 结束管道移动
        this.pipeLayer.reset();
        // 保存分数
        let bestScore = sys.localStorage.getItem("FlappingBirdBest") ?? 0;
        if (score > bestScore) {
            bestScore = score;
            sys.localStorage.setItem("FlappingBirdBest", bestScore);
        }
        this.currentScore.string = score.toString();
        this.bestScore.string = bestScore.toString();
        // 显示结束面板
        tween(this.maskLayer).show().start();
        find("Canvas/Main/Menu/End").active = true;
    }

    private reloadSence(){
        // 获取当前场景的名称
        let currentSceneName = director.getScene().name;
        if(!(currentSceneName && currentSceneName.length > 0)) {
            currentSceneName = "game";
        }
        log("currentScene:", currentSceneName);
        // 卸载当前场景
        director.getScene().destroy();
        // 重新加载同一个场景
        director.loadScene(currentSceneName); 
    }
}


